# -*- coding: latin-1 -*-
'''
Created on 25/02/2011

@author: nmedina
'''
import win32print
import win32api
import os, sys
import string
from reportlab.pdfgen import canvas
import reportlab
from reportlab.lib.pagesizes import letter, A4,landscape
from reportlab.lib.units import inch , cm
from reportlab.graphics.charts.textlabels import Label
from reportlab.platypus import Table , TableStyle
from reportlab.lib.colors import navy, yellow, red ,green,white,black,lemonchiffon,lightblue
import sys
from wx.lib.embeddedimage import PyEmbeddedImage
import random
import math
data= [['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000'],
['24/2/2011', 'DELEGACION QUILMES', 'Mouse Optico', 'Genius', 'XScroll','5','250.0000']]
NAMEMODULE = "informesgastosdependencia"
LIST_STYLE = TableStyle(
[('ALIGN', (0,1), (-1,-1), 'LEFT')
,('BOX',(0,0),(-1,-1),1,black),
('BACKGROUND',(0,0),(3,0),yellow),
('GRID',(0,1),(-1,-1),1,black),
('FONTSIZE',(0,1),(-1,-1),7),
('BOTTOMPADDING',(0,1),(-1,-1),1),
('TOPPADDING',(0,1),(-1,-1),1),
('LEFTPADDING',(0,1),(-1,-1),1)])
class InformesBaseDependencia(canvas.Canvas):
    def __init__(self):
        self.__ErrorDescripcion = ""
        self.__NroError = 0
        self.__NameClase = "InformesGastosxDependencia"
        self.__Metodo = "__init__"
        self.__nombre = ""
        self.SetWidthPositionTable()
        self.SetHeigthPositionTable()
        for i in range(1,15):
            self.__nombre = self.__nombre + random.choice("abcdefghijklmnopqrstuvwxyz1234567890")
        directorio = os.getcwd()+ "/Temp"
        if not os.path.isdir(directorio):
            os.mkdir(directorio)
        self.__ruta = directorio+ "/"+ self.__nombre + ".pdf"
        canvas.Canvas.__init__(self,self.__ruta
                               ,pagesize = landscape(A4) )

    def Cabecera(self):
        try:
            self.__SetError()
            self.__Metodo = "__Cabecera"
            self.roundRect(x = 0.4*cm, y = 18*cm, width = 18.7*cm, height = 2.9*cm, radius = 10 , stroke=1, fill=0)
            self.roundRect(x = 19.2*cm, y = 18*cm, width = 10.1*cm, height = 2.9*cm, radius = 10 , stroke=1, fill=0)
            image = os.getcwd()+ "/osplad.jpg"
            self.drawImage(image,x = 0.5*cm, y = 18.5*cm, width=3*cm,height=1.7*cm)
            return True
        except:
            error = sys.exc_info()[:2]
            self.__MensajeError(error)
            return False
    def SetFilas(self,filas = 33):
        self.__Filas = filas
    def GetFilas(self):
        return self.__Filas
    def SetData(self,data):
        self.__Data = data
    def SetTableStyle(self,style):
        self.__TableStyle = style
    def SetColWidths(self,colWidths):
        self.__ColWidths = colWidths
    def SetHeigthPositionTable(self,h = 0.4*cm ):
        self.__Heigth = h
    def GetHeigthPositionTable(self):
        return self.__Heigth
    def SetWidthPositionTable(self,w = 1*cm ):
        self.__Width= w
    def GetWidthPositionTable(self):
        return self.__Width
    def CreateTable(self):
        try:
            self.__SetError()
            self.__Metodo = "CreateTable"
            colWidths = self.__ColWidths
            self.__CompletarGrilla()
            t = Table(self.__Data,colWidths= colWidths, rowHeights=14, style= self.__TableStyle, splitByRow=1,
                      repeatRows=0, repeatCols=0)
            w, h = t.wrapOn (self, 0.1 * 72,0.1 * 72)
            t.drawOn(self,self.GetHeigthPositionTable(),self.GetWidthPositionTable())
            return True
        except:
            error = sys.exc_info()[:2]
            self.__MensajeError(error)
            return False
      
    def __CompletarGrilla(self):
        try:
            self.__SetError()
            self.__Metodo = "__CompletarGrilla"
            aux = len(self.__Data)
            count = len(self.__Data[1])
            list = []
            for i in range(count):
                list.append("")
            total = self.GetFilas() - aux
            for i in range(aux,self.GetFilas()):
                self.__Data.append(list)
            return True
        except:
            error = sys.exc_info()[:2]
            self.__MensajeError(error)
            return False
    def Printer(self):
        try:
            self.__SetError()
            self.__Metodo = "Printer"
            currentprinter = win32print.GetDefaultPrinter()
            directorio = os.getcwd()+ "/Temp"
            win32api.ShellExecute(0, "print", directorio+ "/"+ self.__nombre + ".pdf", None,  ".",  0)
            return True
        except:
            error = sys.exc_info()[:2]
            self.__MensajeError(error)
            return False
    def View(self):
        try:
            self.__SetError()
            self.__Metodo = "View"
            directorio = os.getcwd()+ "/Temp"
            os.startfile(directorio+ "/"+ self.__nombre + ".pdf" , 'open')
            return True
        except:
            error = sys.exc_info()[:2]
            self.__MensajeError(error)
            raise Exception , self.GetError()
    def _SetMetodo(self,metodo):
        self.__Metodo  = metodo
    def _SetError(self):
        self.__ErrorDescripcion = ""
        self.__NroError = 0 
    def __SetError(self):
        self.__ErrorDescripcion = ""
        self.__NroError = 0 
    def _MensajeError(self,error):
        self.__ErrorDescripcion = "Modulo_" + str(NAMEMODULE)+ "_Clase_" + str(self.__NameClase)+ "_Metodo_" + str(self.__Metodo)
        self.__ErrorDescripcion = self.__ErrorDescripcion + "\nException: " + string.upper(str(error[0]))+ "\n" + string.upper(str(error[1]))
    def __MensajeError(self,error):
        self.__ErrorDescripcion = "Modulo_" + str(NAMEMODULE)+ "_Clase_" + str(self.__NameClase)+ "_Metodo_" + str(self.__Metodo)
        self.__ErrorDescripcion = self.__ErrorDescripcion + "\nException: " + string.upper(str(error[0]))+ "\n" + string.upper(str(error[1]))
    def GetError(self):
        return self.__ErrorDescripcion
    
class InformeGastosDependenciaxPeriodo(InformesBaseDependencia):
    def __init__(self,data,dependencia,periodo,fecha,total):
        self.__Data = data
        self.__NombreInforme = "Gastos de dependencia por Periodo"
        self.__Dependencia = dependencia
        self.__Periodo = periodo
        self.__Fecha = fecha
        self.__Total = total
        self.__style = TableStyle(
                        [('ALIGN', (0,1), (-1,-1), 'LEFT')
                        ,('BOX',(0,0),(-1,-1),1,black),
                        ('BACKGROUND',(0,0),(6,0),lightblue),
                        ('BACKGROUND',(6,1),(6,-1),lemonchiffon),
                        ('GRID',(0,1),(-1,-1),1,black),
                        ('FONTSIZE',(0,1),(-1,-1),7),
                        ('BOTTOMPADDING',(0,1),(-1,-1),1),
                        ('TOPPADDING',(0,1),(-1,-1),1),
                        ('LEFTPADDING',(0,1),(-1,-1),1)])
        InformesBaseDependencia.__init__(self)
        self.SetFilas(32)
        self.SetWidthPositionTable(2*cm)
        if self.__Crear()== True:
            pass
        else:
            raise Exception , self.GetError()
    def __GetCantidadDePaginas(self):
        div = len(self.__Data)/self.GetFilas()
        if div >= 1 :
            mod = math.fmod(len(self.__Data),self.GetFilas())
            if mod != 0:
                return int(div) + 1
            else:
                return int(len(self.__Data)/self.GetFilas())
        else:
            return 1
    def __SetDependencia(self,dependencia = "No especificado"):
        self.__Dependencia = dependencia
    def __GetDependencia(self):
        return self.__Dependencia
    def __SetPeriodo(self,periodo = "No especificado"):
        self.__Periodo = periodo
    def __GetPeriodo(self):
        return self.__Periodo
    def __SetFechaInforme(self,fecha = "No especificado"):
        self.__Fecha = fecha
    def __GetFechaInforme(self):
        return self.__Fecha
    def __SetPagina(self,pagina = "No especificado"):
        self.__Pagina = pagina
    def __GetPagina(self):
        return self.__Pagina
    def __SetTotal(self,total = "No especificado"):
        self.__Total = total
    def __GetTotal(self):
        return self.__Total
    def __SetTitulo(self):
        try:
            self._SetError()
            self._SetMetodo("__SetTitulo")
            self.setFont("Helvetica-Bold", 20)
            self.drawString(5*cm,19.2*cm,self.__NombreInforme)
        except:
            error = sys.exc_info()[:2]
            self._MensajeError(error)
    def __SetDatosDetalle(self):
        try:
            self._SetError()
            self._SetMetodo("__SetTitulo")
            self.setFont("Helvetica-Bold", 14)
            self.drawString(19.5*cm,20.2*cm,"Dependencia: ")
            self.drawString(19.5*cm,19.6*cm,"Periodo: ")
            self.drawString(19.5*cm,19*cm,"Fecha Informe: ")
            self.drawString(19.5*cm,18.4*cm,"Pagina: ")
            self.setFont("Times-Roman", 12)
            self.drawString(23.2*cm,20.2*cm,self.__GetDependencia())
            self.drawString(23.2*cm,19.6*cm,self.__GetPeriodo())
            self.drawString(23.2*cm,19*cm,self.__GetFechaInforme())
            self.drawString(23.2*cm,18.4*cm,self.__GetPagina())
            
        except:
            error = sys.exc_info()[:2]
            self._MensajeError(error)
    def __SetTotal(self):
        try:
            self._SetError()
            self._SetMetodo("__SetTitulo")
            self.setFillColorRGB(251,240,202)
            self.setFillColor(lightblue)
            self.roundRect(x = 0.4*cm, y = 0.5*cm, width = 28.9*cm, height = 1.4*cm, radius = 10 , stroke=1, fill=1)
            self.setFillColor(black)
            self.setFont("Helvetica-Bold", 14)
            self.drawString(0.5*cm,0.9*cm,"Total: ")
            self.setFont("Helvetica-Bold", 14)
            self.drawString(2*cm,0.9*cm,self.__GetTotal())
        except:
            error = sys.exc_info()[:2]
            self._MensajeError(error)
    def __Crear(self):
        try:
            self._SetError()
            self._SetMetodo("__Crear")
            self.__Columnas = ['Fecha', 'Dependencia'
                               , 'Tipo Articulo', 'Fabricante'
                               , 'Modelo','Cantidad','Gasto']
            AddColumn = True
            list = []
            index = 0
            count = 0
            for i in range(len(self.__Data)+ 1):
                count = count + 1
                if len(list)< self.GetFilas() and len(self.__Data)> i:
                    if AddColumn == True:
                        list.append(self.__Columnas)
                        list.append(self.__Data[i])
                        AddColumn = False
                    else:
                        list.append(self.__Data[i])
                else:
                    index = index + 1
                    if i <= len(self.__Data)and len(list)> 0:
                        if self.Cabecera()== True:
                            if len(list)== self.GetFilas():
                                self.SetData(list)
                                self.__SetPagina(str(index)+ " De " + str(self.__GetCantidadDePaginas()))
                                self.__SetTitulo()
                                self.__SetDatosDetalle()
                                self.SetColWidths((50,160,160,160,160,60,70))
                                self.SetTableStyle(self.__style)
                                if len(self.__Data)== self.GetFilas():
                                    self.__SetTotal()
                                if self.CreateTable()== True:
                                    self.showPage()
                                    list = []
                                    AddColumn = True
                                    count = 0
                                else:
                                    raise Exception , self.GetError()
                            elif len(list)< self.GetFilas()and len(list)> 0:
                                self.SetData(list)
                                self.SetFilas(32)
                                self.__SetPagina(str(index)+ " De " + str(self.__GetCantidadDePaginas()))
                                self.SetWidthPositionTable(2*cm)
                                self.__SetTitulo()
                                self.__SetDatosDetalle()
                                self.__SetTotal()
                                self.SetColWidths((50,160,160,160,160,60,70))
                                self.SetTableStyle(self.__style)
                                if self.CreateTable()== True:
                                    self.showPage()
                                    list = []
                                    AddColumn = True
                                    count = 0
                                else:
                                    raise Exception , self.GetError()
                        else:
                            raise Exception , self.GetError()

      
            return True
        except:
            error = sys.exc_info()[:2]
            self._MensajeError(error)
            return False
    
#informe = InformeGastosDependenciaxPeriodo(data,"Consejo Quilmes","25/02/2010 al 25/02/2011","25/02/2011","2500.00")
#informe.save()
#informe.View()